"""
    Author: Yun Mobei
    Modified: 2025-1-5
    Gitee:https://gitee.com/yeea-cn/conn-cumt-net
    
"""
import random
import json
import tkinter as tk
import ttkbootstrap as ttk
from tkinter import messagebox
from ttkbootstrap.constants import *
from ttkbootstrap.scrolled import ScrolledText
import requests

class MainPro():
    def __init__(self,master):
        self.root = master
        self.root.title(config_dict["proname"])
        try:
            self.root.iconphoto(False,tk.PhotoImage(file=config_dict["windowicon"]))
        except:
            pass
        self.root._style = ttk.Style(theme=config_dict["defaulttheme"])#重设主题
        self.root.geometry(config_dict["windowsize"])#self.root.geometry(f"{width}x{height}")
        self.pop_desk_tpl()
        
    def pop_desk_tpl(self):
        """弹出校园网登录配置"""
        fr = ttk.Frame(self.root)
        fr.pack(fill=tk.BOTH,expand=tk.YES)
        nb = ttk.Notebook(fr)
        nb.pack(padx=5, pady=5, fill=tk.BOTH)
        
        tab1 = ttk.Frame(nb)
        self.create_desk_tab1(tab1)
        
        tab2 = ttk.Frame(nb)
        self.create_desk_tab2(tab2)
        
        tab3 = ttk.Frame(nb)
        self.create_desk_tab3(tab3)
        
        nb.add(tab1, text='登录配置')
        nb.add(tab2, text='系统设置')
        nb.add(tab3, text='关于项目')

    def change_style(self):
        """随机更改主题配色"""
        theme = random.choice(self.root.style.theme_names())
        self.root.style.theme_use(theme)
        #print(self.style.colors.get('primary')) #获得当前主题16进制颜色编码

    

    def create_desk_tab1(self,tab1):
        #把变量self.user_account = ttk.StringVar()声明为类变量，加上self，set方法才会生效，不然函数运行结束，变量会丢失
        try:
            with open('apiconfig.json', mode='r', encoding='utf-8') as fp:
                fp_info = fp.read()
                if fp_info:
                    apiconfig_dict = json.loads(fp_info) #将Json字符串解码成python对象   
        except FileNotFoundError:
            apiconfig_dict = {"user_account": "请输入学号", "user_password": "请输入登录密码", "ISP_select": "0"}

        self.user_account= ttk.StringVar(value=apiconfig_dict["user_account"])
        self.user_password = ttk.StringVar(value=apiconfig_dict["user_password"])
        self.ISP_select = ttk.StringVar()
        
        
        lbf = ttk.Labelframe(tab1,text="学生认证登录")
        lbf.pack(anchor="center",padx=10,pady=100)
        
        fr1 = ttk.Frame(lbf)
        fr1.pack(side=tk.TOP,padx=10,pady=10)
        ttk.Label(fr1,text="学号",width=15).pack(side=tk.LEFT)
        e1 = ttk.Entry(fr1,textvariable=self.user_account)
        e1.pack(side=tk.LEFT,fill=tk.X,expand=tk.YES)
        
        fr2 = ttk.Frame(lbf)
        fr2.pack(side=tk.TOP,padx=10,pady=10)
        ttk.Label(fr2,text="密码",width=15).pack(side=tk.LEFT)
        e2 = ttk.Entry(fr2,textvariable=self.user_password)
        e2.pack(side=tk.LEFT,fill=tk.X,expand=tk.YES)
        
        fr3 = ttk.Frame(lbf)
        fr3.pack(side=tk.TOP,padx=10,pady=10)
        isp_list = ["请选择运营商","中国电信","中国移动","中国联通","校园网"]
        lbl = ttk.Label(fr3, text="请选择运营商",width=15)
        lbl.pack(side=tk.LEFT)
        self.isp_cbo = ttk.Combobox(
            master=fr3,
            #text=style.theme.name,
            values=isp_list,
            state="readonly"
        )
        self.isp_cbo.pack(padx=10, side=tk.LEFT)
        self.isp_cbo.current(int(apiconfig_dict["ISP_select"]))
        
        #self.isp_cbo.bind("<<ComboboxSelected>>", self.on_isp_select)

        fr6 = ttk.Frame(lbf)
        fr6.pack(side=tk.TOP,fill=tk.BOTH,padx=10,pady=10)
        ttk.Button(fr6,text="连接", bootstyle="success",command=self.on_submit).pack(side=tk.RIGHT,padx=10,pady=10)
        ttk.Button(fr6,text="重置", bootstyle="secondary",command=self.reset_all).pack(side=tk.RIGHT,padx=10,pady=10)

        
    def on_isp_select(self):
        pass

    def reset_all(self):
        self.user_account.set("")
        self.user_password.set("")
        self.ISP_select.set("")
        
    def on_submit(self):
        isp_list = ["","telecom","cmcc","unicom",""]
        user_account = self.user_account.get() # 学号
        user_password = self.user_password.get() #密码
        ISP_select = isp_list[self.isp_cbo.current()] # 请选择运营商，中国电信：telecom,中国移动：cmcc,中国联通：unicom,校园网：“”（为空）
        furl = f'http://10.2.5.251:801/eportal/?c=Portal&a=login&login_method=1&user_account={user_account}%40{ISP_select}&user_password={user_password}'
        #print(furl)
        conn = ConnNet(furl)
        res = conn.request_link()
        if int(res["result"]) == 1:
            data = {"user_account":self.user_account.get(),"user_password":self.user_password.get(),"ISP_select":self.isp_cbo.current(),"url":furl}      
            with open('apiconfig.json', mode='w', encoding='utf-8') as fp:
                text = json.dumps(data, ensure_ascii=False) #将python字典对象转换成json对象
                fp.write(text)
            messagebox.showinfo("成功","恭喜铁子，校园网登录成功!后续可以不必进入界面，直接运行程序即可自动连接！")
            return
        elif int(res["ret_code"]) ==2:
            messagebox.showerror("提示","铁子有点犟嗷，您已经成功登录，不必重复登录啦！")
            return
        else:
            tip =f"抱歉咯，登录失败，铁子，是不是登录信息没输对啊。错误信息:{res}，如果还是无法登陆，请联系技术人员：1346363063解决！"
            messagebox.showerror("失败",tip)

    def create_desk_tab2(self,tab2):
        labellist = ["程序名称","窗口大小","程序图标","默认主题"]
        self.proname = ttk.StringVar()
        self.windowsize = ttk.StringVar()
        self.windowicon = ttk.StringVar()
        self.defaulttheme = ttk.StringVar()
        self.proname.set(config_dict["proname"])
        self.windowsize.set(config_dict["windowsize"])
        self.windowicon.set(config_dict["windowicon"])
        self.defaulttheme.set(config_dict["defaulttheme"])
        varlist = [self.proname,self.windowsize,self.windowicon,self.defaulttheme]
        self.gen_form(tab2,labellist,varlist)
        

    def gen_form(self,tab2,labellist,varlist):
        formfr = ttk.Frame(tab2)
        formfr.pack(anchor="w")
        for i in range(len(labellist)):
            fr = ttk.Frame(formfr)
            fr.pack(side=tk.TOP,fill=tk.X,expand=tk.YES,pady=5)
            ttk.Label(fr,text=labellist[i],width=12).pack(side=tk.LEFT)
            ttk.Entry(fr,textvariable=varlist[i]).pack(side=tk.LEFT,fill=tk.X,padx=10)

        style = ttk.Style()
        theme_names = style.theme_names()
        theme_selection = ttk.Frame(formfr)
        theme_selection.pack(side=tk.TOP,fill=tk.X, expand=tk.YES,pady=5)

        lbl = ttk.Label(theme_selection, text="选择主题:",width=12)
        lbl.pack(side=tk.LEFT)
        self.theme_cbo = ttk.Combobox(
            master=theme_selection,
            text=style.theme.name,
            values=theme_names,
            state="readonly"
        )
        self.theme_cbo.pack(padx=10, side=tk.LEFT)
        self.theme_cbo.current(theme_names.index(style.theme.name))
        
        self.theme_cbo.bind("<<ComboboxSelected>>", self.change_theme)
        cs = ttk.Button(theme_selection,text='随机主题',bootstyle="outline-success",command=self.change_style).pack(side=tk.LEFT,padx=5)
        btnfr = ttk.Frame(formfr)
        btnfr.pack(side=tk.TOP,fill=tk.BOTH,padx=10,pady=10)

        ttk.Button(btnfr,text="恢复默认", bootstyle="secondary",command=self.recover_all).pack(side=tk.LEFT,padx=10,pady=10)
        ttk.Button(btnfr,text="确定设置", bootstyle="success",command=self.on_submit_setting).pack(side=tk.LEFT,padx=10,pady=10)
        

    def change_theme(self,b=None):
        #print(self.theme_cbo.get())
        self.root.style.theme_use(self.theme_cbo.get())

    def on_submit_setting(self):
        setting_dict = {"proname":self.proname.get(),"windowsize":self.windowsize.get(),"windowicon":self.windowicon.get(),"defaulttheme":self.defaulttheme.get()}
        for i in setting_dict.values():
            if " " in i or i == "":
                messagebox.showerror("失败","有空白项目或意外地输入了空格，请检查！")
                return False
                
        with open('userconfig.json', mode='w', encoding='utf-8') as fp:
            text = json.dumps(setting_dict, ensure_ascii=False) #将python字典对象转换成json对象
            fp.write(text)
        msg = messagebox.askokcancel("成功","设置成功!，确定退出后重新启动应用可以显示！")
        if msg:
            self.root.destroy()
            self.root.quit()
        

    def recover_all(self):
        self.proname.set("CUMT校园网登录")
        self.windowsize.set("800x600")
        self.windowicon.set(".\winicon.png")
        self.defaulttheme.set("superhero")

    def create_desk_tab3(self,tab3):
        self.textbox = ScrolledText(
            master=tab3,
            autohide=True
        )
        self.textbox.pack(fill=BOTH,expand=tk.YES)
        try:
            with open('aboutpro.wit', mode='r', encoding='utf-8') as fp:
                aboutus = fp.read()   
        except FileNotFoundError:
            aboutus = "aboutpro.wit 文件丢失啦，无法显示相关信息，不过不影响程序的使用，技术支持：1346363063 160540168"
        self.textbox.insert(tk.END,aboutus)
        self.textbox._text.configure(state="disabled")
def run_app():
    global config_dict,app
    try:
        with open('userconfig.json', mode='r', encoding='utf-8') as fp:
            fp_info = fp.read()
            if fp_info:
                config_dict = json.loads(fp_info) #将Json字符串解码成python对象   
    except FileNotFoundError:
        config_dict = {"proname":"CUMT校园网登录","windowsize":"800x600","windowicon":".\winicon.png","defaulttheme":"vapor"}
    #print(config_dict)
    app = ttk.Window(iconphoto=config_dict["windowicon"])
    MainPro(app)
    app.mainloop()
    
class ConnNet():
    def __init__(self,url):
        self.url = url

    def request_link(self):
        response = requests.get(self.url)
        if response.status_code == 200:  # 判断请求是否成功，状态码200表示成功
            html_content = response.text
            #print(html_content)
            res_dict = eval(html_content) # res_dict = {"result":"0","msg":"dXNlcmlkIGVycm9yMQ==","ret_code":"1"}，登录成功没有ret_code项
            #print(res_dict["result"],res_dict["msg"],res_dict["ret_code"])
            return res_dict
        else:
            res_dict = {"result":"0","msg":"网络请求失败","ret_code":"1","status_code":f"{response.status_code}"}
            return res_dict

if __name__ == "__main__":
    try:
        with open('apiconfig.json', mode='r', encoding='utf-8') as fp:
            apiconfig = fp.read()
            if apiconfig:
                apiconfig_dict = json.loads(apiconfig) #将Json字符串解码成python对象
            conn = ConnNet(apiconfig_dict["url"])
            res = conn.request_link()
            if int(res["result"]) == 1:
                msg = messagebox.askyesnocancel("成功","恭喜您，校园网登录成功!是否要进入程序界面？")
                if msg:
                    run_app()
                    
            elif int(res["ret_code"]) ==2:
                msg = messagebox.askyesnocancel("提示","您已经成功登录，不必重复登录啦！是否要进入程序界面？")
                if msg:
                    run_app()
            else:
                tip =f"抱歉咯，登录失败，错误信息:{res}，请联系技术人员1346363063解决！是否要进入程序界面进行设置？"
                msg = messagebox.askyesnocancel("失败",tip)
                if msg:
                    run_app()
            #print(res)
    except FileNotFoundError:
        run_app()


